import Error from '@/views/404'
import { lazy, Suspense, useEffect, useState } from 'react'
import { Navigate, useRoutes } from 'react-router-dom'

const Mod: any = import.meta.glob('../views/**/*.tsx') // 在vite中必须这样动态引入所有组件

// 快速导入工具函数
const lazyLoad = (moduleName: string) => {
  const Module = lazy(Mod[`../views/${moduleName}/index.tsx`])

  return (
    <Suspense fallback={<div>Loading...</div>}>
      <Module></Module>
    </Suspense>
  )
}

// 定义默认的路由表
export const defRouter: Array<Router> = [
  // 需要在路由最前面添加 优先匹配 重定向
  {
    path: '/',
    name: '',
    isShow: false,
    element: <Navigate to={'/home'} />
  },
  {
    path: '/login',
    name: '登录',
    isShow: false,
    element: lazyLoad('Login')
  },
  {
    path: '*',
    name: '404',
    isShow: false,
    element: <Error></Error>
  }

  // 这里是后面的异步路由,通过异步导入就是这样,后面我们会进行合并路由
  // {
  //   path: '/home',
  //   name: '主页',
  //   isShow: true,
  //   element: lazyLoad("Home")
  // }
]
// 合并路由
const marRouter = (arr) => {
  return [...defRouter, ...arr]
}

const menu = [
  {
    id: 8,
    name: '主页',
    icon: 'icon-aliens-fill',
    path: '/home',
    component: 'Home', // 上面说到了组件文件夹名大写并在子文件index.tsx中实现
    sort_num: 1,
    redirectTo: '',
    parent_id: null,
    isShow: true,
    create_time: '2023-03-17T08:06:21.283Z'
  }
]

// 根据菜单筛选路由
const filterAsyncRouter = (menus = []) => {
  const addRouter = []
  menus.forEach((item) => {
    const route = {
      name: item.name,
      path: item.path,
      isShow: item.isShow,
      element: ''
    }

    route.element = lazyLoad(item.component)

    if (item.children) {
      route.children = filterAsyncRouter(item.children)
    }

    addRouter.push(route)
  })
  return addRouter
}

const RouterCom = () => {
  const [routerList, setrouterList] = useState([])

  useEffect(() => {
    const asyncArr = filterAsyncRouter(menu)
    const a = marRouter(asyncArr)
    setrouterList(a)
  }, [menu])

  console.log(routerList)
  const routes = useRoutes(routerList)
  return routes
}

export default RouterCom
